package com.zmc.admin.application.impl;

import com.zmc.admin.application.CaptchaService;
import com.zmc.admin.application.LoginApplicationService;
import com.zmc.admin.feign.MemberFeignService;
import com.zmc.admin.feign.ThirdFeignService;
import com.zmc.admin.infrastructure.bean.resp.UserAreaResp;
import com.zmc.admin.infrastructure.bean.vo.common.MetaVo;
import com.zmc.admin.infrastructure.bean.vo.common.RouterVo;
import com.zmc.admin.infrastructure.bean.vo.identity.MerchantInfoVo;
import com.zmc.admin.infrastructure.bean.vo.identity.UserIdentityVo;
import com.zmc.admin.infrastructure.bean.vo.identity.VerifyIdentityVo;
import com.zmc.admin.infrastructure.bean.vo.login.RegisterVo;
import com.zmc.admin.infrastructure.bean.vo.login.VerifyPhoneVo;
import com.zmc.admin.infrastructure.constant.ErrorCodeConstants;
import com.zmc.admin.infrastructure.entity.*;
import com.zmc.admin.infrastructure.enums.UserEnum;
import com.zmc.admin.infrastructure.enums.UserIdentityEnum;
import com.zmc.admin.infrastructure.service.*;
import com.zmc.common.annotation.PreventRepeatSubmit;
import com.zmc.common.domain.query.user.MerchantAddressQuery;
import com.zmc.common.domain.vo.third.SmsVo;
import com.zmc.common.domain.vo.user.UserInfo;
import com.zmc.common.enums.RequestSourceEnum;
import com.zmc.common.exception.base.WebDisplayException;
import com.zmc.common.utils.JsonUtils;
import com.zmc.common.utils.MD5Utils;
import com.zmc.common.utils.redis.RedisCache;
import com.zmc.admin.infrastructure.constant.UserConstants;
import com.zmc.common.utils.ip.IpUtils;
import com.zmc.common.constant.CacheConstants;
import com.zmc.common.constant.Constants;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.common.utils.uuid.IdUtils;
import com.zmc.common.utils.uuid.SnowflakeIdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author：zmc
 * @Date：2024/10/10 13:24
 */

@Service
public class LoginApplicationServiceImpl implements LoginApplicationService {

    public static final Logger log = LoggerFactory.getLogger(LoginApplicationServiceImpl.class);

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService userService;

    @Autowired
    private AuthTokenService authTokenService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysConfigService configService;

    @Autowired
    private ThirdFeignService thirdFeignService;

    @Autowired
    private SysUserIdentityService sysUserIdentityService;

    @Autowired
    private MemberFeignService memberFeignService;


    @Override
    public Map<String, Object> login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(code, uuid);
        // IP黑名单校验
        String blackStr = captchaService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            throw new WebDisplayException("黑名单校验异常");
        }
        // 用户验证
        SysUserEntity sysUser = userService.validateUser(username);
        if (sysUser == null) {
            throw new WebDisplayException(ErrorCodeConstants.USERNAME_PASSWORD_EXCEPTION);
        }
        if (!MD5Utils.verify(password, sysUser.getPassword())){
            throw new WebDisplayException(ErrorCodeConstants.USERNAME_PASSWORD_EXCEPTION);
        }
        log.info("登录成功，userId:{}", sysUser.getUserId());
        //记录登录信息
        recordLoginInfo(sysUser);
        //构建用户信息
        UserInfo user = new UserInfo();
        user.setUserId(sysUser.getUserId());
        user.setDeptId(sysUser.getDeptId());
        user.setUsername(sysUser.getUserName());
        user.setNickName(sysUser.getNickName());
        user.setPhone(sysUser.getPhonenumber());
        user.setMerchantId(sysUser.getMerchantId());
        // 生成token
        Map<String, Object> map = new HashMap<>();
        map.put(Constants.TOKEN, authTokenService.createToken(user));
        return map;
    }

    @Override
    public void logout() {
        UserInfo userInfo = authTokenService.getUserInfo();
        if (StringUtils.isNotNull(userInfo)) {
            String userName = userInfo.getUsername();
            // 删除用户缓存记录
            authTokenService.delUserInfo(userInfo.getToken());
            // 记录用户退出日志
            log.info("username:{}, user.logout.success", userName);
        }
    }

    @Override
    public Map<String, Object> getUserInfo() {

        UserInfo userInfo = authTokenService.getUserInfo();
        SysUserEntity user = userService.getById(userInfo.getUserId());
        // 角色集合
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin(user.getUserId())) {
            roles.add("admin");
        } else {
            List<SysRoleEntity> perms = roleService.selectRolePermissionByUserId(user.getUserId());

            for (SysRoleEntity perm : perms) {
                if (StringUtils.isNotNull(perm)) {
                    roles.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                }
            }
        }
        // 权限集合
        Set<String> permissions = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin(user.getUserId())) {
            permissions.add("*:*:*");
        } else {
            permissions.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return map;
    }

    @Override
    public List<RouterVo> getRouters() {
        List<SysMenuEntity> menus = menuService.selectMenuTreeByUserId(authTokenService.getUserInfo().getUserId());
        return buildMenus(menus);
    }

    @Override
    @Transactional
    @PreventRepeatSubmit(key = "registerVo.username", openSpEL = true)
    public void register(RegisterVo registerVo) {
        String username = registerVo.getUsername();
        String password = registerVo.getPassword();
        String email = registerVo.getEmail();
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setUserName(username);
        sysUser.setEmail(email);
        // 验证码开关
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            validateCaptcha(username, registerVo.getCode(), registerVo.getUuid());
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            throw new WebDisplayException(ErrorCodeConstants.USERNAME_USED_EXCEPTION);
        }
        if (!userService.checkEmailUnique(sysUser)){
            throw new WebDisplayException(ErrorCodeConstants.EMAIL_USED_EXCEPTION);
        }
        sysUser.setNickName(username);
        sysUser.setEmail(email);
        String salt = IdUtils.fastUUID().substring(0, 16);
        String encrypt = MD5Utils.encrypt(password, salt);
        sysUser.setPassword(encrypt);
        sysUser.setSalt(salt);
        sysUser.setIdentityStatus(UserEnum.USER_PHONE_AUTH.getStatus());
        userService.save(sysUser);
    }

    @Override
    public void sendSms(String phone) {
        SysUserEntity sysUser = new SysUserEntity();
        sysUser.setPhonenumber(phone);
        if (!userService.checkPhoneUnique(sysUser)){
            throw new WebDisplayException(ErrorCodeConstants.PHONE_USED_EXCEPTION);
        }
        //验证是否已发送过
        Object codeCache = redisCache.getCacheObject(CacheConstants.SMS_CODE_MEMBER_KEY + phone);
        if (!Objects.isNull(codeCache)) {
            throw new WebDisplayException(ErrorCodeConstants.CODE_HAS_SEND_EXCEPTION);
        }
        SmsVo smsVo = new SmsVo();
        smsVo.setPhone(phone);
        //发送手机号
        thirdFeignService.sendCode(smsVo).valid();
        SmsVo vo = new SmsVo();
        vo.setPhone(phone);
        thirdFeignService.sendCode(vo).valid();
    }

    @Override
    @Transactional
    public void verify(VerifyPhoneVo vo) {
        Object codeCache = redisCache.getCacheObject(CacheConstants.SMS_CODE_MEMBER_KEY + vo.getPhone());
        String code = codeCache.toString();
        if (!code.equals(vo.getCode())) {
            throw new WebDisplayException(ErrorCodeConstants.CAPTCHA_EXCEPTION);
        }
        UserInfo userInfo = authTokenService.getUserInfo();
        SysUserEntity user = userService.getById(userInfo.getUserId());
        if (StringUtils.isEmpty(user.getPhonenumber())) {
            user.setMerchantId(SnowflakeIdUtils.nextSnowFlackId(vo.getPhone()));
        }
        user.setPhonenumber(vo.getPhone());
        if ("1".equals(vo.getType())) {
            user.setIdentityStatus(UserEnum.USER_MERCHANT_INFO.getStatus());
        }
        userService.updateById(user);
    }

    @Override
    @Transactional
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public void identityAuth(VerifyIdentityVo vo) {
        Long userId = authTokenService.getUserInfo().getUserId();
        SysUserIdentityEntity identityEntity = sysUserIdentityService.getByUserId(userId);
        identityEntity.setBusLicense(vo.getBusLicense());
        identityEntity.setCardFront(vo.getCardFront());
        identityEntity.setCardBack(vo.getCardBack());
        identityEntity.setStatus(UserIdentityEnum.USER_IDENTITY_APPROVE.getStatus());
        sysUserIdentityService.updateById(identityEntity);
        SysUserEntity user = userService.getById(userId);
        user.setIdentityStatus(UserEnum.USER_APPROVE.getStatus());
        userService.updateById(user);
    }

    @Override
    @Transactional
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public void enterMerchantInfo(MerchantInfoVo vo) {
        Long userId = authTokenService.getUserInfo().getUserId();
        SysUserIdentityEntity identityEntity = sysUserIdentityService.getByUserId(userId);
        if (identityEntity == null) {
            identityEntity = new SysUserIdentityEntity();
        }
        identityEntity.setUserId(userId);
        identityEntity.setRealName(vo.getRealName());
        identityEntity.setCompany(vo.getCompany());
        identityEntity.setPayAccount(vo.getPayAccount());
        MerchantAddressQuery query = new MerchantAddressQuery();
        query.setAddress(vo.getAddress());
        List<UserAreaResp> areas = JsonUtils.transToArrayClass(memberFeignService.areaDetail(query), UserAreaResp.class);
        identityEntity.setProvince(areas.get(0).getName());
        identityEntity.setProvinceCode(areas.get(0).getCode());
        identityEntity.setCity(areas.get(1).getName());
        identityEntity.setCityCode(areas.get(1).getCode());
        identityEntity.setRegion(areas.get(2).getName());
        identityEntity.setRegionCode(areas.get(2).getCode());
        identityEntity.setPostCode(areas.get(2).getCode());
        identityEntity.setDetailAddress(vo.getDetailAddress());
        identityEntity.setStatus(UserIdentityEnum.USER_IDENTITY.getStatus());
        sysUserIdentityService.saveOrUpdate(identityEntity);
        SysUserEntity user = userService.getById(userId);
        user.setIdentityStatus(UserEnum.USER_IDENTITY_AUTH.getStatus());
        userService.updateById(user);
    }

    @Override
    @Transactional
    @PreventRepeatSubmit(lockByPerson = true, source = RequestSourceEnum.MANAGE)
    public void approve(UserIdentityVo vo) {
        Long userId = vo.getUserId();
        SysUserEntity user = userService.getById(userId);
        SysUserIdentityEntity identityEntity = sysUserIdentityService.getByUserId(userId);
        if ("pass".equals(vo.getResult())) {
            user.setIdentityStatus(UserEnum.USER_IDENTITY_COMPLETE.getStatus());
            identityEntity.setStatus(UserIdentityEnum.USER_IDENTITY_SUCCESS.getStatus());
            //分配角色
            SysRoleEntity sysRoleEntity = roleService.queryByRoleKey("role:merchant");
            if (sysRoleEntity == null) {
                throw new WebDisplayException("请为个体工商户分配角色权限字符串：role:merchant");
            }
            SysUserRoleEntity userRole = new SysUserRoleEntity();
            userRole.setUserId(userId);
            userRole.setRoleId(sysRoleEntity.getRoleId());
            sysUserRoleService.insertUserRole(userRole);
        } else {
            user.setIdentityStatus(UserEnum.USER_IDENTITY_AUTH.getStatus());
            identityEntity.setStatus(UserIdentityEnum.USER_IDENTITY_REJECT.getStatus());
        }
        sysUserIdentityService.updateById(identityEntity);
        userService.updateById(user);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            throw new WebDisplayException(ErrorCodeConstants.CAPTCHA_EXCEPTION);
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new WebDisplayException(ErrorCodeConstants.CAPTCHA_EXCEPTION);
        }
    }

    /**
     * 校验验证码
     *
     * @param code 验证码
     * @param uuid 唯一标识
     */
    public void validateCaptcha(String code, String uuid) {
        boolean captchaEnabled = captchaService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            if (captcha == null) {
                throw new WebDisplayException(ErrorCodeConstants.CAPTCHA_EXCEPTION);
            }
            redisCache.deleteObject(verifyKey);
            if (!code.equalsIgnoreCase(captcha)) {
                throw new WebDisplayException(ErrorCodeConstants.CAPTCHA_EXCEPTION);
            }
        }
    }


    /**
     * 记录登录信息
     *
     * @param sysUser 用户
     */
    public void recordLoginInfo(SysUserEntity sysUser) {
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(LocalDateTime.now());
        userService.updateById(sysUser);
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    public List<RouterVo> buildMenus(List<SysMenuEntity> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenuEntity menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getIsCache().equals(1), menu.getPath()));
            List<SysMenuEntity> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getIsCache().equals(1), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuEntity menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuEntity menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuEntity menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuEntity menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isInnerLink(SysMenuEntity menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuEntity menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }
    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":"},
                new String[]{"", "", "", "/", "/"});
    }
}
